package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.SeckillKeyPrefix;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/seckillGood")
public class SeckillGoodController {
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private RedisService redisService;


    /**
     *
     * 500*10    550-570
     * @return
     */
    @RequestMapping("/query")
    public Result query() {
        //List<Vo>
        //return Result.success(seckillGoodService.query());
        //优化性能,调用redis方法
        return Result.success(seckillGoodService.queryCache());
    }


    @RequestMapping("/queryById")
    public Result queryById(Long seckillId) {
        //seckillGoodVo对象
        //return Result.success(seckillGoodService.queryById(seckillId));
        //优化,在redis中查询
        SeckillGoodVo vo = seckillGoodService.queryByIdCache(seckillId);
        return Result.success(vo);
    }

    @RequestMapping("/initData")
    public String initData(Long seckillId) {
        //将数据库中数据存储到redis中
        //数据中有两条数据 11 12  我11  秒杀上的库存和12秒杀商品的库存都要放到redis中
        //先把数据库中的数据查询出来
        List<SeckillGoodVo> seckillGoodVos = seckillGoodService.query();
        for (SeckillGoodVo seckillGoodVo : seckillGoodVos) {
            //key:stock_count:11,商品的id,data:剩余库存容量
           redisService.set(SeckillKeyPrefix.SECKILL_STOCK_COUNT,seckillGoodVo.getId()+"",seckillGoodVo.getStockCount());
        //在初始化时,就将Vo存储到redis中,前缀+key=redis中的key
            redisService.hset(SeckillKeyPrefix.SECKILL_HASH,"",seckillGoodVo.getId()+"",seckillGoodVo);
        }
        return "初始化成功";
    }







}
